<?php
if (!defined('APP_ID')) { die('No direct script access allowed'); }

/**
 * Route class
 */
class Route {
	private $_pattern = '';
	private $_rules = array();
	private $_defaults = array();
	private $_params = array();
	const REGEX_KEY = '<([a-zA-Z0-9_]++)>';
	
	public function __construct($pattern) {
		$this->_pattern = $pattern;
		return $this;
	}
	
	public function rules($rules, $target = '') {
		$this->_rules = $rules;
		return $this;
	}
	
	public function defaults($defaults, $target = '') {
		$this->_defaults = $defaults;
		$this->_params = Arr::merge($this->_params, $this->_defaults);
		return $this;
	}

	public function check() {
		$this->_params['language'] = Router::getLanguage();
		$this->_params['controller'] = Router::getController();
		$this->_params['action'] = Router::getAction();
		
		//$uri = $this->parse();
		
		return true;
	}
	
	public function parse() {
		// Start with the routed URI
		$uri = $this->_pattern;
		$params = array();

		while (preg_match('#\([^()]++\)#', $uri, $match)) {
			// Search for the matched value
			$search = $match[0];

			// Remove the parenthesis from the match as the replace
			$replace = substr($search, 1, -1);

			while (preg_match('#' . self::REGEX_KEY . '#', $replace, $match)) {
				list($key, $param) = $match;
				if ($this->_params[$param] != $this->_defaults[$param]) {
					// Replace the key with the parameter value
					$replace = str_replace($key, $this->_params[$param], $replace);
				} else {
					// This group has missing parameters
					$replace = '';
					break;
				}
			}
			
			// Replace the group in the URI
			$uri = str_replace($search, $replace, $uri);
		}

		while (preg_match('#' . self::REGEX_KEY . '#', $uri, $match)) {
			list($key, $param) = $match;
			if (!isset($params[$param])) {
				// Look for a default
				if (isset($this->_defaults[$param])) {
					$params[$param] = $this->_defaults[$param];
				} else {
					// Ungrouped parameters are required
					throw new Node_Exception('Required route parameter not passed');
				}
			}
			$uri = str_replace($key, $params[$param], $uri);
		}

		// Trim all extra slashes from the URI
		$uri = preg_replace('#//+#', '/', rtrim($uri, '/'));

		return $uri;
	}
}
